package club.weiyuanstudio.java.eedemo.mybatisdemo.api;

import club.weiyuanstudio.java.eedemo.mybatisdemo.dao.model.Book;
import club.weiyuanstudio.java.eedemo.mybatisdemo.service.BookService;
import club.weiyuanstudio.java.eedemo.mybatisdemo.service.strategy.IllegalBookNameException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class BookAPI {
    BookService bookService;

    @Autowired
    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/book")
    public Object getAllBook() {
        return bookService.getAllBookService();
    }

    @GetMapping("/book/{id}")
    public Object getAllBook(@PathVariable(name = "id") Long id) {
        return bookService.getBookById(id);
    }

    @GetMapping("/search")
    public Object getBookByName(@RequestParam(name = "name") String name) {
        return bookService.getBookByName(name);
    }

    @PostMapping("/book")
    public Object addBook(@RequestBody Book book) {
        Map<String, Object> resultMap = new HashMap<>();

        try {
            bookService.addBook(book.getBookName(), book.getAuthor(), book.getPublicationDate(), book.getPrice());
        } catch (IllegalBookNameException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
        }

        resultMap.put("message", "ok");
        return resultMap;
    }

    @DeleteMapping("/book/{id}")
    public Object deleteBookById(@PathVariable(name = "id") Long id) {
        bookService.deleteBookById(id);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("message", "ok");
        return resultMap;
    }
}
